﻿Function.prototype.bind = function (o) {
    var _f = this;
    return function () {
        return _f.apply(o, arguments);
    };
};

$.fn.outer = function () {
    return $('<div></div>').append(this.eq(0).clone()).html();
};

jQuery.extend(
 {
     evalJSON: function (strJson) {
         return eval("(" + strJson + ")");
     },
     toJSON: function (object) {
         var type = typeof object;
         if ('object' == type) {
             if (Array == object.constructor)
                 type = 'array';
             else if (RegExp == object.constructor)
                 type = 'regexp';
             else
                 type = 'object';
         }
         switch (type) {
             case 'undefined':
             case 'unknown':
                 return;
                 break;
             case 'function':
             case 'boolean':
             case 'regexp':
                 return object.toString();
                 break;
             case 'number':
                 return isFinite(object) ? object.toString() : 'null';
                 break;
             case 'string':
                 return '"' + object.replace(/(\\|\")/g, "\\$1").replace(/\n|\r|\t/g,
       function () {
           var a = arguments[0];
           return (a == '\n') ? '\\n' :
                       (a == '\r') ? '\\r' :
                       (a == '\t') ? '\\t' : ""
       }) + '"';
                 break;
             case 'object':
                 if (object === null) return 'null';
                 var results = [];
                 for (var property in object) {
                     if (object[property] != null) {
                         var value = jQuery.toJSON(object[property]);
                         if (value !== undefined) {
                             results.push(jQuery.toJSON(property) + ':' + value);
                         }
                     } else {
                         results.push(property + ':null');
                     }
                 }
                 return '{' + results.join(',') + '}';
                 break;
             case 'array':
                 var results = [];
                 for (var i = 0; i < object.length; i++) {
                     var value = jQuery.toJSON(object[i]);
                     if (value !== undefined) results.push(value);
                 }
                 return '[' + results.join(',') + ']';
                 break;
         }
     }
 });


$.fieldValue = function (el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
        return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index + 1 : ops.length);
        for (var i = (one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                var v = op.value;
                if (!v)
                    v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

$.fn.setFieldValue = function (sValue) {
    return this.each(function () {
        var t = this.type, tag = this.tagName.toLowerCase(), eEl = this;
        switch (t) {
            case 'hidden':
            case 'text':
            case 'file':
            case 'password':
            case 'textarea':
                this.value = sValue;
                break;
            case 'checkbox':
                var oReg = new RegExp('(^|,) + eEl.value + (,|$)', 'g');
                eEl.checked = oReg.test(sValue);
                break;
            case 'radio':
                if (eEl.value == sValue)
                    eEl.checked = true;
                break;
            case 'select-one':
                for (var j = 0; j < eEl.options.length; j++) {
                    if (eEl.options[j].value == sValue) {
                        eEl.options[j].selected = true;
                        break;
                    }
                }
                break;
        }
    });
};

$.fn.clearForm = function () {
    return this.each(function () {
        $('input,select,textarea', this).clearFields();
    });
};


$.fn.clearFields = $.fn.clearInputs = function () {
    return this.each(function () {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};


$.fn.resetForm = function () {
    return this.each(function () {
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};


$.fn.enable = function (b) {
    if (b == undefined) b = true;
    return this.each(function () {
        this.disabled = !b;
    });
};

$.fn.selected = function (select) {
    if (select == undefined) select = true;
    return this.each(function () {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};


//弹出层
var TipLoading = {
    id: 'I-Loading',
    type: 'Loading',
    message: '数据加载中，请稍后...',
    TipShowType: true,
    width: 160,
    height: 30,
    hasMask: true,

    _createHtml: function () {
        var eId = document.getElementById(this.id);
        if (!eId) {
            if (this.TipShowType) {
                this.width = "160";
            }
            var iTxtHeight = this.height - 12;
            if (iTxtHeight < 0) iTxtHeight = 0;

            //创建元素
            var eTipLoading = $('<div style="display:none"></div>').attr({ "class": "I-Loading", "id": this.id });
            $('body').append(eTipLoading);

            var eMask = $('<div></div>')
            .attr({ "class": "Mask", "id": this.id + '_Mask' }).css("opacity", 0.3);
            eTipLoading.append(eMask);

            var eMaskIframe = $('<iframe></iframe>')
            .attr({ "name": this.id + '_Mask', "id": this.id + '_Iframe', 'src': '#' }).css("opacity", 0.3);
            eMask.append(eMaskIframe);


            var eTag = $('<div></div>')
            .attr({ "class": "Tag", "id": this.id + '_Tag' }).css("width", this.width.toString() + 'px');
            eTipLoading.append(eTag);

            var eTxt = $('<div></div>')
            .attr("class", "Txt").css("height", iTxtHeight.toString() + 'px').html(this.message);
            eTag.append(eTxt);

        }
    },

    show: function () {
        this._createHtml();
        var eTipLoading = document.getElementById(this.id);
        var eTag = document.getElementById(this.id + '_Tag');
        $(eTipLoading).css('display', 'block');

        var eMask = document.getElementById(this.id + '_Mask');
        var eMaskIframe = document.getElementById(this.id + '_Iframe');
        if (this.hasMask) {
            $(eMask).css({ 'width': $(window).width().toString() + 'px', 'height': $(window).height().toString() + 'px', 'display': 'block' });
            $(eMaskIframe).css({ 'width': $(window).width().toString() + 'px', 'height': $(window).height().toString() + 'px' });
        } else {
            $(eMask).css({ 'display': 'none' });
        }
        //设置位置
        var iTop;
        var iLeft;
        if (this.TipShowType) {
            iTop = ($(window).height() - $(eTag).height()) / 2;
            iLeft = ($(window).width() - $(eTag).width()) / 2;
        }
        else {
            iTop = ($(window).height() - $(eTag).height()) / 2;

            iLeft = $(window).width() - 153;
        }
        $(eTag).css('top', iTop.toString() + 'px');
        $(eTag).css('left', iLeft.toString() + 'px');

    },
    hide: function () {
        var eId = document.getElementById(this.id);
        if (eId != null) { eId.style.display = "none"; }
    }
};